//1.引入vue和vue-router
import Vue from "vue"
import VueRouter from "vue-router"
//2.使用路由
Vue.use(VueRouter);
//3.将路由匹配抽离出来
import Home from "@/views/Home.vue";

const searchPopup = () => import("@/views/SearchPopup.vue");

const routes = [{
    path: "",
    redirect: "/home",
  },
  {
    /* 
    这里这个子路径两种写法，一种全部写全，一种直接不要斜杠
    */
    path: "/home", //searchPopup
    component: Home,
    meta: {
      activeNum: 0,
      isShowTabbar: true
    },
    children: [{
      path: "/home/searchPopup",
      name: "searchPopup",
      component: searchPopup
    }]
  },
  {
    path: '/label',
    name: 'Label',
    meta: {
      activeNum: 1,
      isShowTabbar: true
    },
    component: () => {
      return import("@/views/Label.vue")
    }
  },
  {
    path: '/category',
    name: 'Category',
    meta: {
      activeNum: 2,
      isShowTabbar: true
    },
    component: () => {
      return import("@/views/Category.vue")
    }
  },
  {
    path: '/cart',
    meta: {
      activeNum: 3,
      isShowTabbar: true
    },
    component: () => {
      return import("@/views/Cart.vue")
    }
  },
  {
    path: '/user',
    meta: {
      activeNum: 4,
      isShowTabbar: true
    },
    component: () => {
      return import("@/views/User.vue")
    }
  },
  {
    path: '/productDetail',
    component: () => {
      return import("@/views/ProductDetail.vue")
    }
  }
]

const router = new VueRouter({
  routes: routes
})


//4.路由守卫
router.beforeEach((to, from, next) => {
  //4.1要去往的路由对象
  // console.log("to", to);
  //4.2 出发的路由对象
  // console.log("from", from);
  //4.3 放行的路由对象,如果不写就不能去对应的路由
  let token = localStorage.getItem("token");
  if (to.path == "/cart") { //去往购物车页面
    //判断是否登录实际上是判断token是否存在
    if (token) {
      next(); //表示放行
    } else {
      //表示没有登录
      Vue.prototype.$toast("请先登录！");
      setTimeout(() => {
        next("/user")
      }, 1000)
    }
  }
  next();
})

//4.导出路由
export default router;